package com.sgj.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.sgj.common.es.SkuEsModel;
import com.sgj.gulimall.search.config.GulimallElasticSearchConfig;
import com.sgj.gulimall.search.constant.EsConstant;
import com.sgj.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: Guoji Shen
 * @Date: 2021/7/16 10:08
 */
@Slf4j
@Service("productSaveService")
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModelList) throws IOException {

        // 给 es 中建立索引 product，建立好映射关系(使用 resources 中的 product-mapping.txt 内容，在 kibana 中执行)
        // 必须先建立索引，否则数组的存入不是嵌入式(nested)的！！！！！
        // 保存到 es
        BulkRequest bulkRequest = new BulkRequest();
        skuEsModelList.forEach(item -> {
            // 构造保存请求
            IndexRequest request = new IndexRequest(EsConstant.PRODUCT_INDEX);
            request.id(item.getSkuId().toString());
            String jsonString = JSON.toJSONString(item);
            request.source(jsonString, XContentType.JSON);
            bulkRequest.add(request);
        });

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);

        // TODO 如果批量错误
        List<String> idList = Arrays.stream(bulk.getItems())
                .map(item -> item.getId())
                .collect(Collectors.toList());
        log.info("商品上架成功:{}", idList);

        return bulk.hasFailures();
    }
}
